package com.huawei.hmsdemo10086.Activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.huawei.hmsdemo10086.POJO.Result;
import com.huawei.hmsdemo10086.POJO.User;
import com.huawei.hmsdemo10086.R;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegesitActivity extends AppCompatActivity {

    TextView username;
    TextView password;
    TextView phone;

    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regesit);
        username  = (TextView)findViewById(R.id.register_name);
        password = (TextView)findViewById(R.id.register_password);
        phone = (TextView)findViewById(R.id.register_phone);

        Button reg = (Button)findViewById(R.id.register_button);
        intent = this.getIntent();
        //System.out.println(intent.getStringExtra("token"));

        Button back = (Button)this.findViewById(R.id.button_backward);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(RegesitActivity.this,LoginActivity.class);
                startActivity(intent);
                finish();
            }
        });


        reg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!isMobileNO(phone.getText().toString())){
                    Toast.makeText(RegesitActivity.this, "手机号格式不正确", Toast.LENGTH_LONG).show();
                }else if(username.length()<=0){
                    Toast.makeText(RegesitActivity.this, "用户名不能为空", Toast.LENGTH_LONG).show();
                }else if(password.length()<=0){
                    Toast.makeText(RegesitActivity.this, "密码不能为空", Toast.LENGTH_LONG).show();
                }else{
                    insert_test();
                }


            }
        });
    }

    public void bind(int userid)
    {
        String url = "http://10.0.2.2:8443/api/bindUser";
        OkHttpClient mOkHttpClient = new OkHttpClient();

        String json = "{\n" +
                "  \"userid\": \"" + userid + "\",\n" +
                "  \"token\": \"" + intent.getStringExtra("token")+ "\"\n" +
                "}";

        Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"),json)).build();

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("测试", e+"");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }

        });

    }

    private void insert_test()
    {
        String url = "http://10.0.2.2:8443/api/register";
        OkHttpClient mOkHttpClient = new OkHttpClient();

        String json = "{\n" +
                "  \"username\": \"" + username.getText().toString() + "\",\n" +
                "  \"password\": \"" + password.getText().toString() + "\",\n" +
                "  \"phone\": \"" + phone.getText().toString() + "\"\n" +
                "}";


        Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"),json)).build();

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("测试", e+"");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Gson gson = new Gson();
                String rep = response.body().string();
                System.out.println(rep);
                Type type = new TypeToken<Result<User>>(){}.getType();
                Result<User> result = gson.fromJson(rep,type);
                System.out.println(intent.getStringExtra("token"));
                Log.d("reg", result.getCode()+"");
                if(result.getCode()==400)
                {
                    Looper.prepare();
                    Toast.makeText(RegesitActivity.this, "账号已经被注册", Toast.LENGTH_SHORT).show();
                    Looper.loop();
                }else {
                    if (intent.getStringExtra("token") != null) {
                        bind(result.getData().getUserid());
                    }
                    SharedPreferences sharedPreference = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreference.edit();
                    editor.putString("userName", result.getData().getUsername());
                    editor.putString("userId", "" + result.getData().getUserid());
                    editor.putBoolean("isVIP", false);
                    editor.commit();
                    Intent jump_intent = new Intent(RegesitActivity.this, MainActivity.class);
                    startActivity(jump_intent);
                }
            }
        });
    }
    public static boolean isMobileNO(String mobileNums) {
        String telRegex = "^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\\d{8}$";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        return mobileNums.matches(telRegex);
    }



}